package com.lonni.rpc.core.register;

import com.lonni.rpc.core.register.model.Service;
import com.lonni.rpc.core.register.model.ServiceURL;

import java.io.Serializable;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * AbstractServiceRegister：
 * Description:
 *
 * @author: Lonni
 * @date: 2024/7/9 0009 16:55
 */
public abstract class AbstractServiceRegister implements ServiceRegister {

    /**
     * 注册服务
     *
     * @param url
     */
    @Override
    public void register(ServiceURL url) {
        Service service = Service.builder()
                .version(url.getVersion())
                .group(url.getGroup())
                .interfaceName(url.getInterfaceName())
                .build();
        if (!ServiceCache.SERVICE_URLS.containsKey(service)) {
            ServiceCache.SERVICE_URLS.put(service, new ArrayList<ServiceURL>(){{add(url);}});
        }
        //添加到本地
        List<ServiceURL> urls = ServiceCache.SERVICE_URLS.get(service);
        long count = urls.stream().filter(p -> p.getInterfaceName().equals(url.getInterfaceName()) && p.getGroup().equals(url.getGroup()) && p.getVersion().equals(url.getVersion())).count();
        if (count<0){
            ServiceCache.SERVICE_URLS.get(service).add(url);
        }

    }

    /**
     * 删除服务实例
     *
     * @param serviceName
     * @param address
     */
    @Override
    public void unRegister(ServiceURL url) {
        Service service = Service.builder()
                .version(url.getVersion())
                .group(url.getGroup())
                .interfaceName(url.getInterfaceName())
                .build();
        if (ServiceCache.SERVICE_URLS.containsKey(service)) {
            ServiceCache.SERVICE_URLS.get(service).remove(url);
        }
    }
}



